package com.ruoyi.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.system.service.IBkAIService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.BkArticle;
import com.ruoyi.system.service.IBkArticleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 文章信息Controller
 *
 * @author ruoyi
 * @date 2025-01-12
 */
@RestController
@RequestMapping("/bk/article")
public class BkArticleController extends BaseController {
    @Autowired
    private IBkArticleService bkArticleService;

    @Autowired // 修复：添加@Autowired注解
    private IBkAIService bkAIService; // 修复：变量名规范化

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    /**
     * 查询文章信息列表
     */
    @PreAuthorize("@ss.hasPermi('bk:article:list')")
    @GetMapping("/list")
    public TableDataInfo list(BkArticle bkArticle) {
        startPage();
        List<BkArticle> list = bkArticleService.selectBkArticleList(bkArticle);
        return getDataTable(list);
    }

    /**
     * 导出文章信息列表
     */
    @PreAuthorize("@ss.hasPermi('bk:article:export')")
    @Log(title = "文章信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BkArticle bkArticle) {
        List<BkArticle> list = bkArticleService.selectBkArticleList(bkArticle);
        ExcelUtil<BkArticle> util = new ExcelUtil<BkArticle>(BkArticle.class);
        util.exportExcel(response, list, "文章信息数据");
    }

    /**
     * 获取文章信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('bk:article:query')")
    @Anonymous
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bkArticleService.selectBkArticleById(id));
    }

    /**
     * 新增文章信息
     */
    @PreAuthorize("@ss.hasPermi('bk:article:add')")
    @Log(title = "文章信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BkArticle bkArticle) {
        int rows = bkArticleService.insertBkArticle(bkArticle);
        if (rows > 0) {
            // 新增成功后自动生成AI摘要
            try {
                generateAIExcerptForArticle(bkArticle.getId());
            } catch (Exception e) {
                logger.error("自动生成AI摘要失败", e);
                // 摘要生成失败不影响文章新增操作的结果
            }
        }
        return toAjax(rows);
    }

    /**
     * 修改文章信息
     */
    @PreAuthorize("@ss.hasPermi('bk:article:edit')")
    @Log(title = "文章信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BkArticle bkArticle) {
        int rows = bkArticleService.updateBkArticle(bkArticle);
        if (rows > 0) {
            // 修改成功后自动生成AI摘要
            try {
                generateAIExcerptForArticle(bkArticle.getId());
            } catch (Exception e) {
                logger.error("自动生成AI摘要失败", e);
                // 摘要生成失败不影响文章修改操作的结果
            }
        }
        return toAjax(rows);
    }

    /**
     * 删除文章信息
     */
    @PreAuthorize("@ss.hasPermi('bk:article:remove')")
    @Log(title = "文章信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(bkArticleService.deleteBkArticleByIds(ids));
    }

    //    增加浏览量
    @Anonymous
    @PostMapping("/view/{articleId}")
    public void increaseViewCount(@PathVariable Long articleId) {
        try {
            redisTemplate.hasKey("test"); // 验证 Redis 是否连接正常
        } catch (Exception e) {
            System.out.println("Redis 配置可能存在问题：" + e.getMessage());
        }
        System.out.println(">>>> 已接收");
        // 使用Hash结构原子性增加
        redisTemplate.opsForHash().increment("article:views", articleId.toString(), 1);
    }

    /**
     * 生成文章AI摘要的内部方法
     */
    private void generateAIExcerptForArticle(Long id) {
        if (id == null) {
            logger.error("文章ID为空，无法生成AI摘要");
            return;
        }

        BkArticle article = bkArticleService.selectBkArticleById(id);
        if (article == null) {
            logger.error("文章不存在，ID: " + id);
            return;
        }
        String reg = "<img[^>]*>";
        String articleContent = article.getArticleContent();
        String replaced = articleContent.replaceAll(reg, "");
        // 调用AI服务生成摘要
        String aiExcerpt = bkAIService.generateArticleExcerpt(
                replaced,
                article.getArticleTitle()
        );

        // 更新文章摘要
        article.setAiExcerpt(aiExcerpt);
        bkArticleService.updateBkArticle(article);

        logger.info("已为文章 [" + article.getArticleTitle() + "] 生成AI摘要");
    }

    /**
     * 手动触发生成AI摘要（保留原有接口）
     */
    @PreAuthorize("@ss.hasPermi('bk:article:edit')")
    @PostMapping("/generate-ai-excerpt/{id}")
    public AjaxResult generateAIExcerpt(@PathVariable("id") Long id) {
        try {
            BkArticle article = bkArticleService.selectBkArticleById(id);
            if (article == null) {
                return AjaxResult.error("文章不存在");
            }

            // 调用AI服务生成摘要
            String aiExcerpt = bkAIService.generateArticleExcerpt(
                    article.getArticleContent(),
                    article.getArticleTitle()
            );

            // 更新文章摘要
            article.setAiExcerpt(aiExcerpt);
            bkArticleService.updateBkArticle(article);

            Map<String, Object> result = new HashMap<>();
            result.put("aiExcerpt", aiExcerpt);

            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("生成AI摘要失败", e);
            return AjaxResult.error("生成AI摘要失败: " + e.getMessage());
        }
    }
}